package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDto;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    /**
     * 分页查询商机
     */
    @GetMapping("/list")
    public PageDTO<Item> list(@RequestParam("page") Integer page,
                              @RequestParam("size") Integer size) {
        Page<Item> ipage = new Page<>(page, size);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Item::getStatus, 3);
        queryWrapper.orderByAsc(Item::getId);
        Page<Item> itemPage = itemService.page(ipage, queryWrapper);
        return new PageDTO<>(itemPage.getTotal(), itemPage.getRecords());
    }

    /**
     * 根据主键Id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item queryById(@PathVariable(name = "id") Long id) {
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 新增商品
     * @param item
     */
    @PostMapping
    public void save(@RequestBody Item item) {
        if (StringUtils.isEmpty(item.getName())) {
            throw new RuntimeException("名称不能为空");
        }
        item.setStatus(1);
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);
    }

    /**
     * 删除商品,逻辑删除
     * @param id
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable(name = "id") Long id) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(3);
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }

    /**
     * 更新商品
     * @param item
     */
    @PutMapping
    public void update(@RequestBody Item item) {
        item.setStatus(null);
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }

    /**
     * 商品上下架
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateDownOrUp(@PathVariable(name = "id") Long id,
                               @PathVariable(name = "status") Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        item.setUpdateTime(new Date());
        itemService.updateById(item);

    }
}
